package cn.calm.xhtml.spring;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import cn.calm.xhtml.api.TemplateLoader;

public class WebTemplateLoader implements TemplateLoader {
	private String prefix;
	@Resource
	private ServletContext context;

	public WebTemplateLoader() {
	}

	public WebTemplateLoader(ClassLoader classLoader, String prefix) {
		this.prefix = prefix;
	}

	@Override
	public URL loadTemplate(String template) {
		if (template == null) {
			throw new RuntimeException("template is null");
		}
		String temp = getPrefix() + template;
		if (!temp.startsWith("/")) {
			temp = "/" + temp;
		}
		temp = temp.replaceAll("//", "/");
		try {
			String appPath = context.getRealPath("/");
			File file=new File(appPath,temp);
			if(file.isFile()){
				return file.toURI().toURL();
			}else{
				return null;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getPrefix() {
		if (prefix == null) {
			prefix = "";
		}
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

}
